from django.template.loader import render_to_string
from django import template

register = template.Library()

def render_form_field(parser, token):
    try:
        tag_name, field, temp = token.split_contents()
    except ValueError:
        try:
            tag_name, field = token.split_contents()
            temp = 'field'
        except ValueError:
            raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
    
    return FieldRenderer(field, temp)

class FieldRenderer(template.Node):
    def __init__(self, field, temp):
        self.field = template.Variable(field)
        self.temp = temp
        
    def render(self, context):
        try:
            field = self.field.resolve(context)
        except template.VariableDoesNotExist:
            return False
        return render_to_string('forms/%s.html' % self.temp, {'field': field})

register.tag('field', render_form_field)